package handlers

import (
	"github.com/gin-gonic/gin"
	"rbac/cache"
	"rbac/models"
	"rbac/pkg"
	"strconv"
	"time"
)

func UserLogin(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名或者密码为空",
		})
		return
	}

	//判断密码是错误三次
	redis_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return

	}

	//判断用户是否存在
	var user models.User
	models.DB.Where("username = ?", username).First(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	//判断密码是否正确
	if user.Password != pkg.Md5str(password) {

		cache.Rdb.Incr(cache.Ctx, redis_key) //密码错误一次，缓存中的错误次数+1
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2) //密码错误三次，设置过期时间
		}

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"data": user,
		"msg":  "success",
	})
	return
}

func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	models.DB.Create(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
	})
	return
}

func UserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid")) //用户id
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.rid = roles.id
		WHERE
		  user_roles.uid = 1;
	*/
	var role []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid = ?", uid).Debug().Find(&role)

	c.JSON(200, gin.H{
		"code": 200,
		"data": role,
		"msg":  "success",
	})
	return

}

func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid")) //角色id

	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	var node []models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid = ?", rid).Debug().Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"data": node,
		"msg":  "success",
	})
	return

}
